package com.zmn.oms.dubbo.impl.statistics;

import com.alibaba.fastjson.JSON;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.oms.business.interfaces.es.OrderWorkEsBService;
import com.zmn.oms.common.dio.normal.statistics.CompanyStatDIO;
import com.zmn.oms.dubbo.interfaces.statistics.StatOrderCompanyRemoteService;
import com.zmn.oms.dubbo.utils.DubboConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Service;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.data.elasticsearch.core.query.NativeSearchQuery;
import org.springframework.data.elasticsearch.core.query.NativeSearchQueryBuilder;

import javax.validation.Valid;

/**
 * 类描述：订单统计
 *
 * @author heciqi
 * @date 2021/10/28 18:29
 */
@Slf4j
@Service(loadbalance = "roundrobin", timeout = 8000, retries = 0, version = DubboConsts.INTERFACE_VERSION, validation = "true")
public class StatOrderCompanyRemoteServiceImpl implements StatOrderCompanyRemoteService {
    @Autowired
    private OrderWorkEsBService orderWorkEsBService;

    @Override
    public ResponseDTO<Integer> countOrderByQuery(@Valid CompanyStatDIO companyStatDIO) {
        log.info("订单统计-订单按公司统计，入参：{}", companyStatDIO);

        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery()
                .mustNot(QueryBuilders.existsQuery("cancelTime"))
                .mustNot(QueryBuilders.existsQuery("accountTime"));

        queryBuilder.should(QueryBuilders.termQuery("manageCompanyId", companyStatDIO.getCompanyId()));
        queryBuilder.should(QueryBuilders.termQuery("gridManageCompanyId", companyStatDIO.getCompanyId()));
        queryBuilder.minimumShouldMatch(1);

        NativeSearchQueryBuilder nativeSearchQueryBuilder = new NativeSearchQueryBuilder();
        NativeSearchQuery build = nativeSearchQueryBuilder.withQuery(queryBuilder)
                .withPageable(Pageable.unpaged()).build();

        Long count = orderWorkEsBService.countByQuery(build);

        return ResponseDTO.success(count.intValue());
    }
}
